package com.scoy.honeymei.activity.me;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.model.HttpParams;
import com.scoy.honeymei.R;
import com.scoy.honeymei.base.BaseActivity;
import com.scoy.honeymei.bean.OneImgBean;
import com.scoy.honeymei.bean.PersonBean;
import com.scoy.honeymei.custem.AddressPickTask;
import com.scoy.honeymei.fragment.me.NickActivity;
import com.scoy.honeymei.http.HpCallback;
import com.scoy.honeymei.http.HpGo;
import com.scoy.honeymei.install.GlideApp;
import com.scoy.honeymei.url.MeConstant;
import com.scoy.honeymei.url.MyUrl;
import com.scoy.honeymei.utils.GlideEngine;
import com.scoy.honeymei.utils.GlideImgUtil;
import com.scoy.honeymei.utils.MyUtil;
import com.scoy.honeymei.utils.SPHelper;
import com.scoy.honeymei.utils.SystemUtil;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.entity.City;
import cn.qqtheme.framework.entity.County;
import cn.qqtheme.framework.entity.Province;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * @ClassName: PersonActivity$
 * @Description: 基本资料
 * @Author: GaoZhan
 * @CreateDate: 2019/9/11/0011$ 上午 9:13$
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/9/11/0011$ 上午 9:13$
 * @UpdateRemark: 更新内容
 */
public class PersonActivity extends BaseActivity {

    @BindView(R.id.back_iv)
    ImageView backIv;
    @BindView(R.id.title_tv)
    TextView titleTv;
    @BindView(R.id.sign_tv)
    TextView signTv;
    @BindView(R.id.title_llt)
    LinearLayout titleLlt;
    @BindView(R.id.per_img_civ)
    CircleImageView perImgCiv;
    @BindView(R.id.per_nickname_tv)
    TextView perNicknameTv;
    @BindView(R.id.per_sex_tv)
    TextView perSexTv;
    @BindView(R.id.per_part_tv)
    TextView perPartTv;
    @BindView(R.id.per_ok_tv)
    TextView perOkTv;
    private PersonActivity mContext;
    private String nickName;
    private String sexStr;
    private boolean changeif;
    private String imgPhoto;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person);
        ButterKnife.bind(this);
        mContext = PersonActivity.this;

        initNormal();

        httpPerson();

    }

    @Override
    public void initNormal() {
        titleTv.setText(R.string.persondata);

        MyUtil.setStatusBar(mContext, getWindow(), true, R.color.colorWhite);
        titleLlt.setPadding(0, MyUtil.getStatusBarHeight(mContext), 0, 0);
    }

    @OnClick({R.id.back_iv, R.id.per_img_civ, R.id.per_nickname_tv, R.id.per_sex_tv, R.id.per_part_tv, R.id.per_ok_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_iv:
                finish();
                break;
            case R.id.per_img_civ:
                httpUpImg(true);
                break;
            case R.id.per_nickname_tv:
                Intent intent = new Intent(mContext, NickActivity.class);
                if (!TextUtils.isEmpty(perNicknameTv.getText())) {
                    intent.putExtra("name", perNicknameTv.getText().toString());
                }
                startActivityForResult(intent, 0x90);
                break;
            case R.id.per_sex_tv:
                onSexPicker();
                break;
            case R.id.per_part_tv:
                onAddressPicker();
                break;
            case R.id.per_ok_tv:
                if (MyUtil.isFastClick() && changeif) {
                    preClick();
                }
                break;
        }
    }

    /**
     * 选择图片
     *
     * @param isCut 是否裁剪？
     */
    private void httpUpImg(boolean isCut) {
        PictureSelector.create(mContext)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(1)
                .imageSpanCount(3)
                .isCamera(true)
                .isEnableCrop(isCut)
                .imageFormat(PictureMimeType.PNG)
                .isCompress(true)
                .minimumCompressSize(100)
                .withAspectRatio(1, 1)
                .rotateEnabled(false)
                .forResult(0x110);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0x110://图片
                    List<LocalMedia> selectList1 = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia1 = selectList1.get(0);

                    String pathImg = localMedia1.getCompressPath();
                    GlideApp.with(mContext).load(new File(pathImg)).error(R.drawable.ic_nodata).into(perImgCiv);
                    httpOnePic(localMedia1);
                    break;
            }
        }
        switch (resultCode) {
            case 0x90:
                nickName = data.getStringExtra("name");
                changeif = true;
                perNicknameTv.setText(nickName);
                break;
        }

    }

    /**
     * 选择地区
     */
    public void onAddressPicker() {
        AddressPickTask task = new AddressPickTask(this);
        task.setHideProvince(false);
        task.setHideCounty(false);
        task.setCallback(new AddressPickTask.Callback() {
            @Override
            public void onAddressInitFailed() {
                MyUtil.mytoast(mContext, "数据初始化失败");
            }

            @Override
            public void onAddressPicked(Province province, City city, County county) {
                if (county == null) {
                    perPartTv.setText(province.getAreaName() + city.getAreaName());
                } else {
                    perPartTv.setText(province.getAreaName() + city.getAreaName() + county.getAreaName());
                }
                changeif = true;
            }
        });
        task.execute("北京", "北京", "东城");
    }

    //性别
    public void onSexPicker() {
        final Dialog dialog = new Dialog(this, R.style.BottomDialogStyle);
        View view = View.inflate(this, R.layout.dialog_btm_sex, null);
        TextView btmman_tv = (TextView) view.findViewById(R.id.btmman_tv);
        TextView btmwoman_tv = (TextView) view.findViewById(R.id.btmwoman_tv);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (SystemUtil.getScreenWidth(mContext));
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);
        btmman_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                sexStr = "1";
                perSexTv.setText("男");
                changeif = true;

            }
        });

        btmwoman_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                sexStr = "0";
                perSexTv.setText("女");
                changeif = true;
            }
        });
        dialog.show();

    }

    //获取个人信息
    private void httpPerson() {
        HttpParams params = new HttpParams();
        params.put("userid", SPHelper.getString(MeConstant.UID, ""));
        HpGo.newInstance().HttpGo(this, MyUrl.PERSON_DATE, params, new HpCallback() {
            @Override
            public void onSuccess(String o) {
                PersonBean personBean = new Gson().fromJson((String) o, PersonBean.class);
                GlideImgUtil.glidePic(mContext, personBean.getImage(), perImgCiv);
                imgPhoto = personBean.getImage();
                perNicknameTv.setText("".endsWith(personBean.getName()) ? "无名" : personBean.getName());
                perPartTv.setText(personBean.getCity());
                String sexstatus = personBean.getSexstatus();// "性别 0女 1男",
                sexStr = sexstatus;
                if ("0".equals(sexstatus)) {
                    perSexTv.setText("女");
                } else if ("1".equals(sexstatus)) {
                    perSexTv.setText("男");
                } else {
                    perSexTv.setText("女");
                    sexStr = "0";
                }

            }

            @Override
            public void onFailed(String code, String msg, String o) {
                MyUtil.mytoast(mContext, code + "," + msg);
            }

            @Override
            public void onError(int code, String errorMsg) {
                MyUtil.mytoast(mContext, errorMsg);
            }
        });

    }


    private void preClick() {
        if (TextUtils.isEmpty(perPartTv.getText())) {
            MyUtil.mytoast(mContext, "请选择城市");
            return;
        }

        httpPersonEdit();
    }

    //编辑个人信息
    private void httpPersonEdit() {
        HttpParams params = new HttpParams();
        params.put("userid", SPHelper.getString(MeConstant.UID, ""));
        params.put("image", imgPhoto);
        params.put("name", perNicknameTv.getText().toString());
        params.put("sexstatus", sexStr);
        params.put("city", perPartTv.getText().toString());
        HpGo.newInstance().HttpGo(this, MyUrl.PERSON_EDIT, params, new HpCallback() {
            @Override
            public void onSuccess(String o) {
                setResult(0x787);
                finish();
            }

            @Override
            public void onFailed(String code, String msg, String o) {
                MyUtil.mytoast(mContext, code + "," + msg);
            }

            @Override
            public void onError(int code, String errorMsg) {
                MyUtil.mytoast(mContext, errorMsg);
            }
        });

    }

    private void httpOnePic(LocalMedia media) {

        HttpParams params = new HttpParams();
        params.put("file", new File(media.getCompressPath()));

        HpGo.newInstance().HttpGo(this, MyUrl.SINGLE_IMGUP, params, new HpCallback() {
            @Override
            public void onSuccess(String o) {
                OneImgBean oneImgBean = new Gson().fromJson(o, OneImgBean.class);
                imgPhoto = oneImgBean.getFilePath();
                changeif = true;
            }

            @Override
            public void onFailed(String code, String msg, String o) {
                MyUtil.mytoast(mContext, code + "|" + msg);
            }

            @Override
            public void onError(int code, String errorMsg) {
                MyUtil.mytoast(mContext, errorMsg);
            }
        });

    }


}
